package com.zzj.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zzj.annotation.LogAnnotation;
import com.zzj.annotation.ViewCountAnnotation;
import com.zzj.base.Result;
import com.zzj.entity.Post;
import com.zzj.model.dto.post.PostCreateDto;
import com.zzj.model.dto.post.PostUpdateDto;
import com.zzj.model.dto.QueryListDto;
import com.zzj.service.IPostService;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 文章表 前端控制器
 * </p>
 *
 * @author zzj
 * @since 2023-07-17
 */
@RestController
@RequestMapping("/post")
public class PostController {
    @Resource
    private IPostService postService;

    @LogAnnotation(name = "创作文章", description = "创作文章")
    @Transactional
    @PostMapping("create")
    public Result create(@RequestBody @Validated PostCreateDto in) {
        Post post = postService.create(in);
        return Result.success("创作成功", post);
    }

    @LogAnnotation(name = "更新文章", description = "更新文章")
    @Transactional
    @PostMapping("update")
    public Result update(@Validated @RequestBody PostUpdateDto in) {
        Post post = postService.update(in);
        return Result.success("更新成功", post);
    }

    @LogAnnotation(name = "查询文章列表", description = "分页查询文章列表")
    @Transactional
    @PostMapping("queryList")
    public Result queryList(@RequestBody @Validated QueryListDto in) {
        IPage<Post> categoryIPage = postService.queryList(in);
        return Result.success(categoryIPage);
    }

    @LogAnnotation(name = "删除文章", description = "根据ID删除文章")
    @Transactional
    @PostMapping("remove")
    public Result<?> remove(@RequestParam(value = "id") int id) {
        boolean b = postService.removeById(id);
        if (!b) {
            return Result.error("删除失败");
        }
        return Result.success("删除成功");
    }

    @LogAnnotation(name = "查询文章", description = "根据ID查询文章")
    @Transactional
    @PostMapping("id")
    public Result<?> id(@RequestParam(value = "id") int id) {
        Post byId = postService.getById(id);
        return Result.success(byId);
    }
    @LogAnnotation(name = "浏览文章", description = "浏览量自动加1")
    @ViewCountAnnotation
    @Transactional
    @PostMapping("view")
    public Result<?> view(@RequestParam(value = "id") int id) {
        Post byId = postService.getById(id);
        return Result.success(byId);
    }
}
